package org.springblade.modules.admin.event;

import lombok.extern.slf4j.Slf4j;
import org.springblade.modules.admin.entity.RescueNoticeTask;
import org.springblade.modules.admin.service.IRescueNoticeTaskService;
import org.springblade.modules.system.entity.TenantConfig;
import org.springblade.modules.system.service.TenantConfigService;
import org.springblade.modules.system.vo.config.AlarmNotifyConfig;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.annotation.Resource;

/**
 * @Author ysq
 * @Date 2025/07/10
 * @Description 救援困人通知监听器
 */
@Slf4j
@Component
public class RescueTrappedNoticeListener {

	@Resource
	private IRescueNoticeTaskService rescueNoticeTaskService;
	@Resource
	private TenantConfigService tenantConfigService;

	@Async
	@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT, classes = RescueTrappedNoticeEvent.class, fallbackExecution = true)
	public void onNoticeEvent(RescueTrappedNoticeEvent event) {
		// 读取困人报警通知配置
		TenantConfig tenantConfig = tenantConfigService.getTenantConfig(event.getNoticeParam().getTenantId());
		if (tenantConfig == null) {
			return;
		}
		AlarmNotifyConfig alarmNotifyConfig = tenantConfig.getAlarmNotifyConfig();
		if (alarmNotifyConfig == null || !alarmNotifyConfig.getAlarmNotifyEnabled()) {
			return;
		}

		try {
			// 创建救援通知任务
			int round = 1;
			RescueNoticeTask task = new RescueNoticeTask();
			task.setRescueNoticeId(event.getNoticeParam().getRescueNoticeId());
			task.setCurrentRound(round);
			task.setAlarmNotifyConfig(alarmNotifyConfig);
			if(rescueNoticeTaskService.save(task)) {
				// 通知一轮
				rescueNoticeTaskService.notifyRound(task, round);
			}
		} catch (Exception e) {
			log.error("RescueTrappedNoticeListener 救援困难通知事件执行出错", e);
		}

	}
}
